const crypto = require('crypto')
const cryptoJs = require('crypto-js')

function md5(str) {
  // 注意参数需要为 String 类型，否则会出错
  return crypto.createHash('md5').update(String(str)).digest('hex')
}

// aes解密
function aesDecrypt(str, key, iv) {
  const hex = cryptoJs.enc.Base64.stringify(cryptoJs.enc.Hex.parse(str))
  const decrypted = cryptoJs.AES.decrypt(hex, key, {
    iv,
    mode: cryptoJs.mode.CBC,
    padding: cryptoJs.pad.Pkcs7,
  })
  return decrypted.toString(cryptoJs.enc.Utf8)
}

// aes加密
function aesEncrypt(str, key, iv) {
  const encrypted = cryptoJs.AES.encrypt(str, key, {
    iv,
    mode: cryptoJs.mode.CBC,
    padding: cryptoJs.pad.Pkcs7,
  })
  return encrypted.ciphertext.toString()
}

module.exports = {
  md5,
  aesDecrypt,
  aesEncrypt,
}
